package org.soenea.doitall.domain.command;

import org.dsrg.soenea.domain.command.CommandError;
import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.command.DomainCommand;
import org.dsrg.soenea.domain.helper.Helper;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.model.group.Group;
import org.soenea.doitall.domain.model.group.mapper.GroupInputMapper;
import org.soenea.doitall.domain.model.user.User;
import org.soenea.doitall.domain.model.user.mapper.UserInputMapper;

public class DeleteGroupCommand extends DomainCommand {

	public DeleteGroupCommand(Helper helper) {
		super(helper);
	}

	@Override
	public void setUp() throws CommandException {
	}

	@Override
	public void process() throws CommandException {
		try {
			long id = (Long)helper.getSessionAttribute("GroupID");
			Group group = GroupInputMapper.find(id);
			UoW.getCurrent().registerRemoved(group);
			
			for(User user : UserInputMapper.findByGroupID(id))
			{
				user.setGroupID(0);
				UoW.getCurrent().registerDirty(user);
			}
			
			UoW.getCurrent().commit();
			
			helper.setRequestAttribute("groups", GroupInputMapper.findAll());
		} catch (Exception e) {
			throw new CommandException(e);
		}
	}

	@Override
	public void tearDown() throws CommandError {
	}

}
